<?php
require_once('Model/SiteManage.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
class Model_News
{
    private   $sys;
    public    $config;
    protected $table_name;
    protected $setting_table_name;
    protected $category_table_name;

    public function __construct($plugin='news')
    {
        $this->sys        = new Model_SiteManage();
        $config           = __get_config('plugin.ini');
        
        if($plugin=='news')
        {
            $this->config     = $config['MANAGE_NEWS'];
            $this->table_name          = 'M_NEWS';
            $this->setting_table_name  = 'D_NEWS_SETTING';
            $this->category_table_name = 'D_NEWS_CATEGORY';
        }
        elseif($plugin=='eiwa_weekly')
        {
            $this->config     = $config['EIWA_WEEKLY'];
            $this->table_name          = 'Z_EIWA_WEEKLY';
            $this->setting_table_name  = 'D_EIWA_WEEKLY_SETTING';
            $this->category_table_name = 'D_EIWA_WEEKLY_CATEGORY';
        }
        elseif($plugin=='eiwa_life')
        {
            $this->config     = $config['EIWA_LIFE'];
            $this->table_name          = 'Z_EIWA_LIFE';
            $this->setting_table_name  = 'D_EIWA_LIFE_SETTING';
            $this->category_table_name = 'D_EIWA_LIFE_CATEGORY';
        }
    }
    //
    public function insert($data)
    {
        $db = new Model_DB();
        if(!isset($data['site_id'])){
            $data['site_id'] = $this->sys->getCurrentSite();
        }
        return $db->insert($this->table_name, $data);
    }
    public function update($id, $data)
    {
        $db = new Model_DB();
        return $db->update($id, $this->table_name, $data);
    }
    public function get($id)
    {
        $db = new Model_DB();
        $sql = sprintf("select * from ".$this->table_name." where site_id = %d and id = %d", $this->sys->getCurrentSite(), $db->escape($id));
        $db->query($sql);
        return $db->fetch();
    }
    public function delete($id)
    {
        $db   = new Model_DB();
        $data = array();
        $data['id']      = $id;
        $data['site_id'] = $this->sys->getCurrentSite();
        return $db->delete($this->table_name, $data);
    }
    public function getListCount($data)
    {
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select count(*) from {$this->table_name}";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "");
        $db->query($sql);
        if ($db->res){
            return array_shift($res = $db->fetch());
        }
        return false;
    }
    public function getList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {
        $list  = array();
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select * from {$this->table_name}";
        $sql  .= (!empty($where) ? " where " . implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
        $db->query($sql);
        if ($db->res){
            while($res = $db->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    }
    private function createSearchCondition($data, $prefix = '')
    {
        $db    = new Model_DB();
        $where = array();
        if ($prefix != ''){
            $prefix = $prefix . '.';
        }
        if(!isset($data['site_id'])){
            $where[] = "{$prefic}site_id = {$this->sys->getCurrentSite()}";
        }
        else{
            $where[] = '1 = 1';
        }
        foreach($db->getFieldList($this->table_name) as $key => $_){
            if (isset($data[$key]) && $data[$key] !== ''){
                
                if(is_array($data[$key]))//データが配列の場合
                {
                    foreach($data[$key] as $one)
                    {
                        $value = $db->escape($one);
                        $tmp[$key][] = "{$prefix}{$key} = '{$value}'";
                    }
                    $where[] = implode(" OR ", $tmp[$key]);
                }
                else
                {
                    $value = $db->escape($data[$key]);
                    if ($key == 'title'){
                        $where[] = "{$prefix}{$key} collate utf8_unicode_ci like '%{$value}%'";
                    }else{
                        $where[] = "{$prefix}{$key} = '{$value}'";
                    }
                }
            }
        }
        return $where;
    }
    public function validate(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'status,date,title,type');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        }
        //
        if ($data['type'] == 0){
            $key = 'page_text';
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        }
        elseif ($data['type'] == 1){
            $key = 'url';
            if($data[$key] == '' || $validate->Uri($data[$key])) {
                $err[$key]['Uri'] = true;
            }
        }
        
        return empty($err);
    }
    public function getCategory($news_id)
    {
        $db  = new Model_DB();
        $sql = sprintf("select * from {$this->category_table_name} where news_id = %d order by sort_order asc", $news_id);
        $db->query($sql);
        $category = array();
        while($res = $db->fetch()){
            $category[] = $res['category_id'];
        }
        return $category;
    }
    public function updateCategory($news_id, $category)
    {
        $db = new Model_DB();
        $db->delete($this->category_table_name, array('news_id' => $news_id));
        $sort_order = 0;
        foreach($category as $category_id){
            $sort_order ++;
            $data                = array();
            $data['news_id']     = $news_id;
            $data['category_id'] = $category_id;
            $data['sort_order']  = $sort_order;
            $db->insert($this->category_table_name, $data);
        }
    }
    //
    public function getSetting($site_id = '')
    {
        if ($site_id == ''){
            $site_id = $this->sys->getCurrentSite();
        }
        $db  = new Model_DB();
        $sql = "select * from {$this->setting_table_name} where site_id = {$site_id}";
        $db->query($sql);
        $setting = array();
        if ($db->num_rows() > 0){
            $setting = $db->fetch();
            $setting['top_items']  = explode(',', $setting['top_items']);
            $setting['list_items'] = explode(',', $setting['list_items']);
        }
        else{
            // default values
            $setting['top_nums']   = 3;
            $setting['top_items']  = array('date','title');
            $setting['list_nums']  = 10;
            $setting['list_items'] = array('date','title');
            $setting['sort_item']  = 'date';
        }
        return $setting;
    }
    public function validateSetting(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'content_name,top_nums,top_items,list_nums,list_items,sort_item');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        }
        return empty($err);
    }
    public function updateSetting($data, $site_id = '')
    {
        if ($site_id == ''){
            $site_id = $this->sys->getCurrentSite();
        }
        $data['site_id'] = $site_id;
        $db = new Model_DB();
        $db->replace($this->setting_table_name, $data);
    }
    //　状態
    public function getStatusMap()
    {
        $map    = array();
        $map[2] = '仮登録';
        $map[1] = '公開';
        $map[0] = '非公開';
        return $map;
    }
    //　種別
    public function getTypeMap()
    {
        $map    = array();
        $map[0] = 'ページ';
        $map[1] = '外部リンク';
        $map[2] = 'ファイル';
        $map[3] = 'なし';
        return $map;
    }
    //　時間
    public function getTimeMap()
    {
        for($i=0; $i<24; $i++)
        {
            $map[$i] = $i;
        }
        return $map;
    }
    //　表示項目
    public function getItemsMap()
    {
        $map              = array();
        $map['date']      = '日付';
        $map['title']     = 'タイトル';
        $map['sub_title'] = 'サブタイトル';
        $map['file1']     = 'サムネイル画像';
        return $map;
    }
    //　表示順
    public function getSortMap()
    {
        $map           = array();
        $map['date']   = '日付順';
        $map['r_date'] = '登録日順';
        $map['u_date'] = '更新日順';
        return $map;
    }
    //
    public function getFormKeys()
    {
        $db = new Model_DB();
        return array_keys($db->getFieldList($this->table_name));
    }
    //
    public function getThumbDir($mkdir = true)
    {
        $thumb_dir = $this->sys->getCurrentSiteDir() . '/' . $this->config['thumb_dir'];
        if ($mkdir == true){
            $this->sys->createDir($thumb_dir);
        }
        return SiteManageRootDir . '/htdocs/' . $thumb_dir;
    }
    public function getThumbUrl()
    {
        return $this->sys->getCurrentSiteUrl() . '/' . $this->config['thumb_dir'];
    }
    public function getFileDir($mkdir = true)
    {
        $file_dir = $this->sys->getCurrentSiteDir() . '/' . $this->config['file_dir'];
        if ($mkdir == true){
            $this->sys->createDir($file_dir);
        }
        return SiteManageRootDir . '/htdocs/' . $file_dir;
    }

    
    
    
    /*
     * 公開側制御
     */
    public function getDisplayTopNewsList($site_id, $category_id = '')
    {
        $setting = $this->getSetting($site_id);
        $list    = array();
        
        // リスト取得ロジックは分離予定
        $db = new Model_DB();
        $sql = "SELECT *
                FROM {$this->table_name} N
                LEFT JOIN {$this->category_table_name} C ON N.id = C.news_id
                WHERE site_id = '{$site_id}' and status = 1 and
                      (st_time is null or st_time <= current_timestamp or st_time = '0000-00-00 00:00:00') and
                      (ed_time is null or ed_time > current_timestamp or ed_time = '0000-00-00 00:00:00') ";
        if($category_id != '')
        {
            if(is_array($category_id))
            {
                foreach($category_id as $one)
                {
                    if(is_array($one)) return false;
                    $tmp[] = $db->escape($one);
                }
                $sql .= "and C.category_id in ('".implode("','", $tmp)."') ";
            }
            else
            {
                $sql .= "and C.category_id = '{$db->escape($category_id)}' ";
            }
        }
            
        $sql .= "ORDER BY {$setting['sort_item']} desc limit {$setting['top_nums']}";
        
        $db->query($sql);
        while($res = $db->fetch()){
            $row['id'] = $res['id'];
            $row['type'] = $res['type'];
            $row['url'] = $res['url'];
            foreach($setting['top_items'] as $key){
                if (isset($res[$key])){
                    $row[$key] = $res[$key];
                }
            }
            $list[] = $row;
        }
        
        return $list;
    }
    public function getDisplayNewsList($site_id, $category_id = '')
    {
        $setting = $this->getSetting($site_id);
        $list    = array();

        // リスト取得ロジックは分離予定
        $db = new Model_DB();                
        $sql = "SELECT *
                FROM {$this->table_name} N
                LEFT JOIN {$this->category_table_name} C ON N.id = C.news_id
                WHERE site_id = '{$site_id}' and status = 1 and
                      (st_time is null or st_time <= current_timestamp or st_time = '0000-00-00 00:00:00') and
                      (ed_time is null or ed_time > current_timestamp or ed_time = '0000-00-00 00:00:00') ";
        if($category_id != '')
        {
            if(is_array($category_id))
            {
                foreach($category_id as $one)
                {
                    if(is_array($one)) return false;
                    $tmp[] = $db->escape($one);
                }
                $sql .= "and C.category_id in ('".implode("','", $tmp)."') ";
            }
            else
            {
                $sql .= "and C.category_id = '{$db->escape($category_id)}' ";
            }
        }
            
        $sql .= "ORDER BY {$setting['sort_item']} desc limit {$setting['list_nums']}";
        
        $db->query($sql);
        while($res = $db->fetch()){
            $row['id'] = $res['id'];
            $row['type'] = $res['type'];
            $row['url'] = $res['url'];
            foreach($setting['list_items'] as $key){
                if (isset($res[$key])){
                    $row[$key] = $res[$key];
                }
            }
            $list[] = $row;
        }
    
        return $list;
    }
    
    /**
     *
     * サイドメニュー表示用のデータを返す
     * return array[$year] = ($month1, $month2, ...);
     * 
     */
    public function getArchivesList($site_id, $category_id = '')
    {
        $setting = $this->getSetting($site_id);
        $list = array();

        $db = new Model_DB();
        $sql = "SELECT N.id, N.date, YEAR(date) AS `year`, MONTH(date) AS `month`, DAY(date) AS `day`
                FROM {$this->table_name} N
                LEFT JOIN {$this->category_table_name} C ON N.id = C.news_id
                WHERE site_id = '{$site_id}' and status = 1 and
                      (st_time is null or st_time <= current_timestamp or st_time = '0000-00-00 00:00:00') and
                      (ed_time is null or ed_time > current_timestamp or ed_time = '0000-00-00 00:00:00') ";
        if($category_id != '')
        {
            if(is_array($category_id))
            {
                foreach($category_id as $one)
                {
                    if(is_array($one)) return false;
                    $tmp[] = $db->escape($one);
                }
                $sql .= "and C.category_id in ('".implode("','", $tmp)."') ";
            }
            else
            {
                $sql .= "and C.category_id = '{$db->escape($category_id)}' ";
            }
        }
        $sql .= "ORDER BY {$setting['sort_item']} desc";
            
        $db->query($sql);
        while($res = $db->fetch()){            
            $list[$res['year']][$res['month']][$res['day']][] = array('id'=>$res['id'], 'date'=>$res['date']);
        }
    
        if(count($list) === 0)
            return false;
        else
            return $list;
    }
    
    /**
     *
     * 指定された年月のニュースリストを返す
     * （とりあえず）該当年月全件表示
     */
    public function getNewsList($site_id, $year, $month, $category_id = '')
    {
        if(!checkdate($month, $day=1, $year))
            return false;
                
        $setting = $this->getSetting($site_id);
        $list    = array();

        $db = new Model_DB();        
        $sql = "SELECT N.*
                FROM {$this->table_name} N
                LEFT JOIN {$this->category_table_name} C ON N.id = C.news_id
                WHERE site_id = '{$site_id}' and status = 1 and
                      (st_time is null or st_time <= current_timestamp or st_time = '0000-00-00 00:00:00') and
                      (ed_time is null or ed_time > current_timestamp or ed_time = '0000-00-00 00:00:00') and
                      YEAR(date) = {$year} and MONTH(date) = {$month} ";
        if($category_id != '')
        {
            if(is_array($category_id))
            {
                foreach($category_id as $one)
                {
                    if(is_array($one)) return false;
                    $tmp[] = $db->escape($one);
                }
                $sql .= "and C.category_id in ('".implode("','", $tmp)."') ";
            }
            else
            {
                $sql .= "and C.category_id = '{$db->escape($category_id)}' ";
            }
        }
        $sql .= "ORDER BY {$setting['sort_item']} desc";
        $db->query($sql);
        while($res = $db->fetch()){
            $row['id'] = $res['id'];
            $row['type'] = $res['type'];
            $row['url'] = $res['url'];
            foreach($setting['list_items'] as $key){
                if (isset($res[$key])){
                    $row[$key] = $res[$key];
                }
            }
            $list[] = $row;
        }

        if(count($list) === 0)
            return false;
        else
            return $list;
    }
    
    public function getNews($site_id, $id)
    {
        $db = new Model_DB();
        $sql = sprintf("SELECT N.*, C.category_id FROM ".$this->table_name." N
                        LEFT JOIN {$this->category_table_name} C ON N.id = C.news_id
                        WHERE N.site_id = %d and N.id = %d", $site_id, $db->escape($id));
        $db->query($sql);
        return $db->fetch();
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
?>